package com.autumn.aitraffic.controller;

import com.autumn.aitraffic.api.Result;
import com.autumn.aitraffic.domain.po.*;
import com.autumn.aitraffic.domain.vo.*;
import com.autumn.aitraffic.service.CarListService;
import com.autumn.aitraffic.service.impl.*;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("violate")
public class ViolateController {
    @Autowired
    private CarListService carListService;

    @GetMapping("getCarList")
    public Result getCatViolateListvo( @RequestParam(required = false) Integer crossName, // 改为Integer包装类型
                                       @RequestParam Integer vioType,                    // vioType必填，保持Integer
                                       @RequestParam String startDate,
                                       @RequestParam String endDate) {
        // 检查并设置默认日期值
        if (startDate == null || startDate.trim().isEmpty()) {
            startDate = LocalDate.now().minusWeeks(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        if (endDate == null || endDate.trim().isEmpty()) {
            endDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        
        LocalDate date = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDateTime startTime = date.atStartOfDay();
        LocalDate enddate = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDateTime endTime = enddate.atStartOfDay();
        
        // 使用新的car_list表查询数据
        List<CarList> carList = carListService.lambdaQuery()
                //.eq(crossName != 0, CarList::getCrossName, crossName + "号路口")
//                .eq(crossName != 0, CarList::getCrossName, crossName)
//                .eq(vioType != 0, CarList::getVioCause, vioType)
                .eq(crossName != null && crossName != 0, CarList::getIntersection, crossName) // 判空+非零
                .eq(vioType != 0, CarList::getVioCause, vioType) // vioType=0表示查询所有类型      // 同理处理vioType
                .ne(vioType == 0, CarList::getVioCause, 5) // 新增排除条件
                .between(CarList::getVioTime, startTime, endTime)
                .orderByDesc(CarList::getVioTime)
                .list();
        
        CarListResultVo carListResultVo = new CarListResultVo();
        CarListNumVo carListNumVo = new CarListNumVo();
        ArrayList<CarListVo> carListVos = new ArrayList<>();
        
        // 统计各类型违规数量
        for (CarList car : carList) {
            CarListVo carListVo = new CarListVo();
            carListVo.setId(car.getId());
            carListVo.setCarType(car.getCarType());
            carListVo.setCarImage(car.getCarImage());
            carListVo.setVioCause(car.getVioCause());
            carListVo.setPlateNum(car.getPlateNum());
            carListVo.setVioTime(car.getVioTime());
            //carListVo.setCrossName(car.getCrossName());
            carListVo.setCrossName(car.getIntersection() + "号路口");
            carListVos.add(carListVo);
            
            // 更新统计数量
            carListNumVo.setSum(carListNumVo.getSum() + 1);
            switch (car.getVioCause()) {
                case 1:
                    carListNumVo.setType1(carListNumVo.getType1() + 1);
                    break;
                case 2:
                    carListNumVo.setType2(carListNumVo.getType2() + 1);
                    break;
                case 3:
                    carListNumVo.setType3(carListNumVo.getType3() + 1);
                    break;
                case 4:
                    carListNumVo.setType4(carListNumVo.getType4() + 1);
                    break;
            }
        }
        
        carListResultVo.setList(carListVos);
        carListResultVo.setNum(carListNumVo);
        return Result.succ(null, carListResultVo);
    }

    public CarListResultVo getCatViolateList(Integer crossName, Integer vioType, String startDate, String endDate) {
        // 检查并设置默认日期值
        if (startDate == null || startDate.trim().isEmpty()) {
            startDate = LocalDate.now().minusWeeks(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        if (endDate == null || endDate.trim().isEmpty()) {
            endDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        
        LocalDate date = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDateTime startTime = date.atStartOfDay();
        LocalDate enddate = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDateTime endTime = enddate.atStartOfDay();
        
        // 使用新的car_list表查询数据
        List<CarList> carList = carListService.lambdaQuery()
                //.eq(crossName != 0, CarList::getCrossName, crossName + "号路口")
//                .eq(crossName != 0, CarList::getCrossName, crossName)
//                .eq(vioType != 0, CarList::getVioCause, vioType)
                .eq(crossName != null && crossName != 0, CarList::getIntersection, crossName) // 判空+非零
                .eq(vioType != null && vioType != 0, CarList::getVioCause, vioType)        // 同理处理vioType
                .ne(vioType == 0, CarList::getVioCause, 5) // 新增排除条件
                .between(CarList::getVioTime, startTime, endTime)
                .orderByDesc(CarList::getVioTime)
                .list();
        
        CarListResultVo carListResultVo = new CarListResultVo();
        CarListNumVo carListNumVo = new CarListNumVo();
        ArrayList<CarListVo> carListVos = new ArrayList<>();
        
        // 统计各类型违规数量
        for (CarList car : carList) {
            CarListVo carListVo = new CarListVo();
            carListVo.setId(car.getId());
            carListVo.setCarType(car.getCarType());
            carListVo.setCarImage(car.getCarImage());
            carListVo.setVioCause(car.getVioCause());
            carListVo.setPlateNum(car.getPlateNum());
            carListVo.setVioTime(car.getVioTime());
            //carListVo.setCrossName(car.getCrossName());
            carListVo.setCrossName(car.getIntersection() + "号路口");
            carListVos.add(carListVo);
            
            // 更新统计数量
            carListNumVo.setSum(carListNumVo.getSum() + 1);
            switch (car.getVioCause()) {
                case 1:
                    carListNumVo.setType1(carListNumVo.getType1() + 1);
                    break;
                case 2:
                    carListNumVo.setType2(carListNumVo.getType2() + 1);
                    break;
                case 3:
                    carListNumVo.setType3(carListNumVo.getType3() + 1);
                    break;
                case 4:
                    carListNumVo.setType4(carListNumVo.getType4() + 1);
                    break;
            }
        }
        
        carListResultVo.setList(carListVos);
        carListResultVo.setNum(carListNumVo);
        return carListResultVo;
    }
    
    @GetMapping("getStatistics")
    public Result getStatics(@RequestParam("startDate") String startDate,
                             @RequestParam("endDate") String endDate
    ) {
        // 检查参数是否为空，为空则设置默认值
        if (startDate == null || startDate.trim().isEmpty()) {
            // 默认开始时间为当前年月减去1个月
            startDate = YearMonth.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
        }
        if (endDate == null || endDate.trim().isEmpty()) {
            // 默认结束时间为当前年月
            endDate = YearMonth.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
        }
        
        DateTimeFormatter YEAR_MONTH_FORMATTER =
                DateTimeFormatter.ofPattern("yyyy-MM");
        YearMonth yearMonth = YearMonth.parse(startDate, YEAR_MONTH_FORMATTER);
        LocalDateTime localDateTimestart = yearMonth.atDay(1).atStartOfDay();// 示例结果：2024-02-01T00:00
        YearMonth yearMonth2 = YearMonth.parse(endDate, YEAR_MONTH_FORMATTER);
        LocalDateTime localDateTimeend = yearMonth2.atEndOfMonth().atTime(LocalTime.MAX);
        
        // 创建list4存储每个路口的违章总数
        List<Integer> list4 = new ArrayList<>();
        // 最多统计6个路口
        for(int i=1; i<=6; i++) {
            CarListResultVo catViolateList =
                    getCatViolateList(i, 0, startDate + "-01", endDate + "-" + yearMonth2.lengthOfMonth());
            
            // 计算当前路口的违章总数并添加到list4
            int crossTotal = catViolateList.getNum().getType1() + 
                              catViolateList.getNum().getType2() + 
                              catViolateList.getNum().getType3() + 
                              catViolateList.getNum().getType4();
            list4.add(crossTotal);
        }
        
        StaticsVo staticsVo = new StaticsVo();
        ArrayList<Integer> integers1 = new ArrayList<>();
        
        // 统计所有类型的违规总数
        int num1 = 0, num2 = 0, num3 = 0, num4 = 0;
        for(int i=1; i<=6; i++) {
            CarListResultVo catViolateList =
                    getCatViolateList(i, 0, startDate + "-01", endDate + "-" + yearMonth2.lengthOfMonth());
            num1 += catViolateList.getNum().getType1();
            num2 += catViolateList.getNum().getType2();
            num3 += catViolateList.getNum().getType3();
            num4 += catViolateList.getNum().getType4();
        }
        
        integers1.add(num1);
        integers1.add(num2);
        integers1.add(num3);
        integers1.add(num4);
        staticsVo.setList1(integers1);
        
        // 按月统计违规总数
        YearMonth currentMonth = yearMonth;
        ArrayList<Integer> integers2 = new ArrayList<>();
        
        // 创建list3存储每个月的各类型违规数量
        List<List<Integer>> list3 = new ArrayList<>();
        
        while (!currentMonth.isAfter(yearMonth2)) {
            String monthStr = currentMonth.format(YEAR_MONTH_FORMATTER);
            int daysInMonth = currentMonth.lengthOfMonth();
            
            int monthTotal = 0;
            int monthType1 = 0;
            int monthType2 = 0; 
            int monthType3 = 0;
            int monthType4 = 0;
            
            for(int i=1; i<=6; i++) {
                // 设置当月的开始和结束日期
                CarListResultVo monthViolateList = 
                        getCatViolateList(i, 0, monthStr + "-01", 
                        monthStr + "-" + daysInMonth);
                
                // 累加当月所有类型的违规总数
                monthType1 += monthViolateList.getNum().getType1();
                monthType2 += monthViolateList.getNum().getType2();
                monthType3 += monthViolateList.getNum().getType3();
                monthType4 += monthViolateList.getNum().getType4();
                
                monthTotal += monthViolateList.getNum().getType1();
                monthTotal += monthViolateList.getNum().getType2();
                monthTotal += monthViolateList.getNum().getType3();
                monthTotal += monthViolateList.getNum().getType4();
            }
            
            // 添加当月的各类型违规数量
            List<Integer> monthTypeCounts = new ArrayList<>();
            monthTypeCounts.add(monthType1);
            monthTypeCounts.add(monthType2);
            monthTypeCounts.add(monthType3);
            monthTypeCounts.add(monthType4);
            list3.add(monthTypeCounts);
            
            integers2.add(monthTotal);
            // 移动到下一个月
            currentMonth = currentMonth.plusMonths(1);
        }
        
        staticsVo.setList2(integers2);
        staticsVo.setList3(list3);
        staticsVo.setList4(list4);
        
        return Result.succ(null, staticsVo);
    }
}
